package cn.lcsjsxy.yxz.day.Practice.Reflection;

import java.lang.reflect.Method;

//反射调用类的方法
public class Invoke_a_class_method_via_reflection {
    public static class User{
        //
        public String username;
        private String password;
        protected int age;
        String email;

        //无参无返回值
        public void showInfo(){
            System.out.println("用户名: " + username);
        }
        //有参有返回值(私有)
        private String getEncryptedPassword(String salt){
            return password + "_" + salt;
        }
        // 静态方法
        public static void printVersion() {
            System.out.println("User 类版本：v1.0");
        }
    }

    public static void main(String[] args) throws Exception{
        Class<?> userClass = User.class;
        User user = (User) userClass.newInstance();

        user.username = "yang";
        user.age = 16;

        //调用showInfo方法
        Method showInfoMethod = userClass.getMethod("showInfo");
        showInfoMethod.invoke(user);
        //调用私有方法getEncryptedPassword(String)
        java.lang.reflect.Field passwordField = userClass.getDeclaredField("password");
        passwordField.setAccessible(true);
        passwordField.set(user, "123456");

        // 获取私有方法
        Method encryptedMethod = userClass.getDeclaredMethod("getEncryptedPassword", String.class);
        // 设置私有方法可访问
        encryptedMethod.setAccessible(true);
        // 调用方法并传入参数
        String result = (String) encryptedMethod.invoke(user, "abc123");
        System.out.println("加密后的密码：" + result);

        // 3. 调用静态方法printVersion()
        Method printVersionMethod = userClass.getMethod("printVersion");
        // 静态方法调用时，invoke的第一个参数可以为null
        printVersionMethod.invoke(null);
    }
}
